﻿using Prism.Commands;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SIMS.Common.RestClient;
using SIMS.Common.Models;
using Newtonsoft.Json;
using SIMS.Shared.DTO;
using SIMS.Shared.Models;

namespace SIMS.ClassesModule.ViewModels
{
    public class AddEditClassesViewModel : BindableBase, IDialogAware
    {
        private readonly HttpRestClient _httpClient;

        public AddEditClassesViewModel(HttpRestClient httpClient)
        {
            _httpClient = httpClient;
        }

        private ClassesDTO classes;

        public ClassesDTO Classes
        {
            get { return classes; }
            set { SetProperty(ref classes, value); }
        }

        private List<StudentDTO> monitors;

        public List<StudentDTO> Monitors
        {
            get { return monitors; }
            set { SetProperty(ref monitors, value); }
        }

        private StudentDTO monitor;

        public StudentDTO Monitor
        {
            get { return monitor; }
            set { SetProperty(ref monitor, value); }
        }

        private DelegateCommand loadedCommand;

        public DelegateCommand LoadedCommand
        {
            get
            {
                if (loadedCommand == null)
                {
                    loadedCommand = new DelegateCommand(Loaded);
                }
                return loadedCommand;
            }
        }

        private async void Loaded()
        {
            this.Monitors = new List<StudentDTO>();
            if (Classes?.Id > 0) { 
                var pagingModel = await GetStudentsByClasses(Classes.Id);
                if (pagingModel != null)
                {
                    var entities = pagingModel.Items;
                    Monitors.AddRange(entities);
                    //如果有班长，则为班长赋值
                    if (Classes.Monitor > 0)
                    {
                        this.Monitor = this.Monitors?.FirstOrDefault(r => r.Id == Classes.Monitor);
                    }
                }
            }
        }

        private async Task<PagingModel<StudentDTO>?> GetStudentsByClasses(int? classId)
        {
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters["classId"] = classId;
           
            ApiRequest request = new ApiRequest();
            request.Method = RestSharp.Method.Get;
            request.Parameters = parameters;
            request.Route = Api.STUDENT_GETSTUDENTSBYCLASSES;
            ResponseResultModel response = await _httpClient.Execute(request);
            if (response.code == 1)
            {
                var students = JsonConvert.DeserializeObject<PagingModel<StudentDTO>>(JsonConvert.SerializeObject(response.data));
                return students;
            }
            return null;
        }

        private DelegateCommand cancelCommand;

        public DelegateCommand CancelCommand
        {
            get
            {
                if (cancelCommand == null)
                {
                    cancelCommand = new DelegateCommand(Cancel);
                }
                return cancelCommand;
            }
        }

        private void Cancel()
        {
            RequestClose?.Invoke((new DialogResult(ButtonResult.Cancel)));
        }

        private DelegateCommand saveCommand;

        public DelegateCommand SaveCommand
        {
            get
            {
                if (saveCommand == null)
                {
                    saveCommand = new DelegateCommand(Save);
                }
                return saveCommand;
            }
        }

        private async void Save() 
        {
            if (Classes != null) 
            {
                Classes.CreateTime = DateTime.Now;
                Classes.LastEditTime = DateTime.Now;
                if (Monitor != null)
                {
                    Classes.Monitor = Monitor.Id;
                }
                else
                { 
                    Classes.Monitor = null;
                }
                bool flag = false;
                if (Classes.Id > 0) {
                   flag = await UpdateClasses(Classes);
                }
                else
                { 
                   flag = await AddClasses(Classes);
                }
                if (flag)
                {
                    RequestClose?.Invoke((new DialogResult(ButtonResult.OK)));
                }
            }
        }

        private async Task<bool> AddClasses(ClassesDTO classInfo)
        {
            ApiRequest request = new ApiRequest();
            request.Method = RestSharp.Method.Post;
            request.Parameters = classInfo;
            request.Route = Api.CLASSES_ADDCLASSES;
            ResponseResultModel response = await _httpClient.Execute(request);
            if (response.code == 1)
            {
                long r = (long)response.data;
                return r == 1;
            }
            return false;
        }

        private async Task<bool> UpdateClasses(ClassesDTO classInfo)
        {
            ApiRequest request = new ApiRequest();
            request.Method = RestSharp.Method.Put;
            request.Parameters = classInfo;
            request.Route = Api.CLASSES_UPDATECLASSES;
            ResponseResultModel response = await _httpClient.Execute(request);
            if (response.code == 1)
            {
                long r = (long)response.data;
                return r == 1;
            }
            return false;
        }

        public string Title => "新增或编辑班级信息";

        public event Action<IDialogResult> RequestClose;

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {
            
        }

        public void OnDialogOpened(IDialogParameters parameters)
        {
            if (parameters != null && parameters.ContainsKey("classes"))
            {
                var classes = parameters.GetValue<ClassesDTO>("classes");
                this.Classes = (ClassesDTO)classes.Clone();
            }
            else 
            { 
                this.Classes = new ClassesDTO();
            }
        }

    }
}
